package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 预约设置服务
 */
@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 批量导入预约设置
     *
     * @param list
     */
    @Override
    public void add(List<OrderSetting> list) {
        //遍历判断数据是否已存在
        if (list != null && list.size() > 0) {
            for (OrderSetting orderSetting : list) {
                int count = orderSettingDao.findCountByDate(orderSetting);
                if (count > 0) {
                    //存在则更新数据
                    orderSettingDao.update(orderSetting);
                } else {
                    //不存在再添加数据
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    /**
     * 查询预约信息
     *
     * @param date
     * @return
     */
    @Override
    public List<Map> getOrderSettingByMonth(String date) {
        date = date+"%";
        List<OrderSetting> orderSettingList = orderSettingDao.getOrderSettingByMonth(date);
        //数据转换便于前端展示
        List<Map> mapList = new ArrayList<>();
        if (orderSettingList != null && orderSettingList.size() > 0) {

            for (OrderSetting orderSetting : orderSettingList) {
                Map<String, Object> map = new HashMap<>();
                map.put("date", orderSetting.getOrderDate().getDate());
                map.put("number", orderSetting.getNumber());
                map.put("reservations", orderSetting.getReservations());
                mapList.add(map);
            }
        }
        return mapList;
    }

    /**
     * 编辑按钮修改预约信息
     * @param orderSetting
     * @return
     */
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //查询预约信息是否存在
        int countByDate = orderSettingDao.findCountByDate(orderSetting);
        //判断与预约信息是否存在
        if (countByDate >0) {
            //预约信息存在，更新预约信息
            orderSettingDao.update(orderSetting);
        } else {
            //预约信息不存在，新增预约信息
            orderSettingDao.add(orderSetting);
        }
    }

    /**
     * 删除当天之前的数据
     */
    @Override
    public void delete() throws Exception {
        Date date = new Date();
        String s = DateUtils.parseDate2String(date);
        //System.out.println(s);

      orderSettingDao.delete(s);
    }
}
